import { defaultConfig } from './config.js';

// 安装完成后弹出通知
chrome.runtime.onInstalled.addListener(() => {
  console.log('插件已安装');
});

chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
  if (msg.cmd === 'DO_TRANSLATE') {
    // 临时存储
    chrome.storage.session.set({selectedText: msg.text}).then(() => {
      // 打开弹窗（MV3 只能后台调）
      console.log('>>>收到请求准备开始调用翻译接口');
      performTranslation(msg.text).then(translation => {
        // 获取当前活动标签页并发送翻译结果
        chrome.tabs.query({active: true, currentWindow: true}, (tabs) => {
          if (tabs.length > 0) {
            chrome.tabs.sendMessage(tabs[0].id, {
              cmd: 'SHOW_TRANSLATION',
              translation: translation
            });
          }
        });
      });
    });
    sendResponse({success: true});
  }
});

// 添加翻译函数
async function performTranslation(text) {
  // 调用翻译接口
  let translation;
  try {
    // 从本地存储获取配置
    const result = await chrome.storage.local.get(['config']);
    const config = result.config || defaultConfig;  // 使用公共配置
    
    // 使用配置中的参数
    const apiUrl = config.apiUrl || defaultConfig.apiUrl;
    const apiKey = config.apiKey || defaultConfig.apiKey;
    const sourceLang = config.sourceLang || defaultConfig.sourceLang;
    const targetLang = config.targetLang || defaultConfig.targetLang;
    const translateRole = config.translateRole || defaultConfig.translateRole;

    const response = await fetch(apiUrl, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${apiKey}`, // 替换为实际的 API key
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        "inputs": {
          "query": text,
          "from": sourceLang,
          "to": targetLang,
          "role": translateRole
        },
        "user": "abc-123"
      })
    });

    if (response.ok) {
      const data = await response.json();
      // 显示翻译结果
      translation = data.answer;
    } else {
      console.error('Translation API error:', response.status);
      translation = '翻译失败';
    }
  } catch (error) {
    console.error('Network error:', error);
    translation = '网络错误';
  }
  return translation;
}